package com.pyl.admin.system.service.impl;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.SqlHelper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.pyl.admin.core.constant.AdminConst;
import com.pyl.admin.core.enums.ResultEnum;
import com.pyl.admin.core.enums.StatusEnum;
import com.pyl.admin.core.enums.UserIsRoleEnum;
import com.pyl.admin.core.exception.ResultException;
import com.pyl.admin.core.shiro.ShiroUtil;
import com.pyl.admin.core.web.PageUtil;
import com.pyl.admin.core.web.PageUtil.PageSort;
import com.pyl.admin.system.entity.SysDept;
import com.pyl.admin.system.entity.SysUser;
import com.pyl.admin.system.entity.SysUserRole;
import com.pyl.admin.system.mapper.SysDeptMapper;
import com.pyl.admin.system.mapper.SysUserMapper;
import com.pyl.admin.system.mapper.SysUserRoleMapper;
import com.pyl.admin.system.service.SysUserService;
import com.pyl.admin.system.validator.UserForm;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.util.ObjectUtil;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 灵魂贰婶
 * @since 2019-06-28
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {

	@Autowired
	private SysUserMapper sysUserMapper;

	@Autowired
	private SysDeptMapper sysDeptMapper;

	@Autowired
	private SysUserRoleMapper sysUserRoleMapper;

	@Override
	public PageInfo<SysUser> selectUserListPage( Integer status, String query,
			Long deptId) {
		PageSort pageSort = PageUtil.pageRequest();
		PageHelper.startPage(pageSort.getCurrent(), pageSort.getSize());
		PageHelper.orderBy(pageSort.getOrderByColumn()+ " " + pageSort.getIsAsc());
		List<SysUser> list = sysUserMapper.selectUserListPage(status, query, deptId);
		PageInfo<SysUser> pageInfo = new PageInfo<SysUser>(list);
		return pageInfo;
	}

	@Override
	@Transactional
	public boolean saveOrUpdate(UserForm userForm) {

		SysDept sysDept = sysDeptMapper.selectById(userForm.getDept());
		// 修改
		if (ObjectUtil.isNotNull(userForm.getId())) {
			// 不允操作管理员数据
			if (userForm.getId().equals(AdminConst.ADMIN_ID)
					&& !ShiroUtil.getSubject().getId().equals(AdminConst.ADMIN_ID)) {
				throw new ResultException(ResultEnum.NO_ADMIN_AUTH);
			}
			SysUser sysUser = sysUserMapper.selectById(userForm.getId());
			// 属性空时忽略不注入
			BeanUtil.copyProperties(userForm, sysUser, CopyOptions.create().setIgnoreNullValue(true));
			sysUser.setDeptId(sysDept.getId());
			sysUser.setDeptName(sysDept.getTitle());
			sysUser.setUpdateDate(new Date());
			return SqlHelper.retBool(sysUserMapper.updateById(sysUser));
		}
		// 新增用户
		// 判断账号是否重复
		SysUser sysUser = new SysUser().setUsername(userForm.getUsername());
		if (ObjectUtil.isNotNull(sysUserMapper.selectOne(sysUser))) {
			// 账号重复
			throw new ResultException(ResultEnum.USER_EXIST);
		}

		// 判断密码是否为空
		if (userForm.getPassword().isEmpty() || "".equals(userForm.getPassword().trim())) {
			throw new ResultException(ResultEnum.USER_PWD_NULL);
		}

		// 判断两次密码是否一致
		if (!userForm.getPassword().equals(userForm.getConfirm())) {
			throw new ResultException(ResultEnum.USER_INEQUALITY);
		}

		// 对密码进行加密
		String salt = ShiroUtil.getRandomSalt();
		String encrypt = ShiroUtil.encrypt(userForm.getPassword(), salt);
		sysUser = new SysUser();
		// 拷贝属性 忽略null值
		BeanUtil.copyProperties(userForm, sysUser, CopyOptions.create().setIgnoreNullValue(true));
		sysUser.setPassword(encrypt);
		sysUser.setSalt(salt);
		sysUser.setCreateDate(new Date());
		sysUser.setUpdateDate(new Date());
		sysUser.setDeptId(sysDept.getId());
		sysUser.setStatus(Integer.valueOf(StatusEnum.OK.getCode()));
		sysUser.setDeptName(sysDept.getTitle());
		return SqlHelper.retBool(sysUserMapper.insert(sysUser));
	}

	@Override
	public SysUser selectUserAndRoleById(Long id) {

		return sysUserMapper.selectUserAndRoleById(id);
	}

	@Override
	@Transactional
	public boolean updateStatus(StatusEnum statusEnum, List<Long> idList) {
		// 删除用户时取消与角色的关联
		SysUser sysUser = new SysUser();
		if (statusEnum == StatusEnum.DELETE) {
			for (int i = 0; i < idList.size(); i++) {
				sysUserRoleMapper.delete(new EntityWrapper<SysUserRole>().eq("user_id", idList.get(i)));
			}
			sysUser.setIsRole(Integer.valueOf(UserIsRoleEnum.NO.getCode()));
		}
		sysUser.setStatus(Integer.valueOf(statusEnum.getCode()));
		sysUser.setUpdateDate(new Date());
		return SqlHelper.retBool(sysUserMapper.update(sysUser, new EntityWrapper<SysUser>().in("id", idList)));
	}

	@Override
	public List<SysUser> selectLocalUserByRoleId(String roleId) {
		return sysUserMapper.selectUserByRoleId(roleId, Integer.valueOf(StatusEnum.OK.getCode()));
	}

	@Override
	public SysUser selectOneByUserName(String username) {
		return sysUserMapper.selectOneByUserName(username);
	}

}
